package com.chukong.sdk.provider;

import java.io.File;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;

import com.chukong.sdk.common.Log;
import com.chukong.sdk.util.CommonUtil;

public class DBHelper extends SQLiteOpenHelper {

    private static final String CREATE_TASK_TABLE =
            "CREATE TABLE IF NOT EXISTS " + DBConstant.TABLE_DOWNLOAD_STAT
            + "("
            + DBConstant._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + DBConstant.STAT_APKNAME + " TEXT,"
            + DBConstant.STAT_PKGNAME + " TEXT,"
            + DBConstant.STAT_APKLABEL + " TEXT,"
            + DBConstant.STAT_APKVERNAME + " TEXT,"
            + DBConstant.STAT_APKVERCODE + " INTEGER,"
            + DBConstant.STAT_DOWNTIME + " LONG,"
            + DBConstant.FOO + " text"
            + ")";

    private static final String DROP_TASK_TABLE = "DROP TABLE " + DBConstant.TABLE_DOWNLOAD_STAT + " IF EXISTS";

    private Context mContext;
    public DBHelper(Context context) {
        super(context,getMyDatabaseName(context), null, DBConstant.DB_VERSION);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try{
            db.execSQL(CREATE_TASK_TABLE);
        }catch(SQLException e){
            Log.d(Log.TAG, "error : " + e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if(newVersion > oldVersion){
            try {
                db.execSQL(DROP_TASK_TABLE);
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                onCreate(db);
            }
        }
    }

    private static String getMyDatabaseName(Context context) {
        String databasename = DBConstant.DB_NAME;
        boolean isSdcardEnable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {// SDCard是否插入
            isSdcardEnable = true;
        }
        String dbPath = null;
        if (isSdcardEnable) {
            dbPath = CommonUtil.getSingleton().getDBdir();;
        } else {// 未插入SDCard，建在内存中
            dbPath = context.getFilesDir().getPath() + "/database/";
        }
        File dbp = new File(dbPath);
        if (!dbp.exists()) {
            dbp.mkdirs();
        }
        File dbName = new File(dbPath, DBConstant.DB_NAME);
        databasename = dbName.getAbsolutePath();
        return databasename;
    }
}
